<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PDF转图片(多页单张图)</title>
  </head>

  <body>
    <!-- 用于显示图片的容器 -->
    <div id="pdf-container"></div>

    <!-- 引入本地的pdf.js和pdf.worker.js -->
    <script src="./js/pdf.min.js"></script>
    <script>
      pdfjsLib.GlobalWorkerOptions.workerSrc = "./js/pdf.worker.min.js";

      // PDF文件的URL
      // const pdfUrl = "http://localhost:8080/servlet/cert?cert_id=229&itm_id=193&tkh_id=0&isShowPrefix=false&lan=zh-cn";
      const pdfUrl = "./pdf/test.pdf";
      // const pdfUrl = "./pdf/cert2.pdf";

      // 加载PDF文件并转换为图片
      pdfjsLib.getDocument(pdfUrl).promise.then(function (pdf) {
        const numPages = pdf.numPages;
        const pdfContainer = document.getElementById("pdf-container");

        // 存储每一页的 canvas
        const pageCanvases = [];
        let totalHeight = 0;
        let maxWidth = 0;

        // 遍历每一页并转换为 canvas
        const loadPagePromises = [];
        for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
          console.log("pageNumber", pageNumber);
          console.log("pdf.getPage(pageNumber)", pdf.getPage(pageNumber));

          const pagePromise = pdf.getPage(pageNumber).then(function (page) {
            const scale = 1;
            const viewport = page.getViewport({ scale: scale });

            const canvas = document.createElement("canvas");
            const context = canvas.getContext("2d");
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            const renderContext = {
              canvasContext: context,
              viewport: viewport,
            };

            return page.render(renderContext).promise.then(function () {
              pageCanvases.push(canvas);
              // pageCanvases.unshift(canvas);
              totalHeight += canvas.height;
              maxWidth = Math.max(maxWidth, canvas.width);
            });
          });

          loadPagePromises.push(pagePromise);
          // loadPagePromises.unshift(pagePromise);
        }

        // 当所有页面都渲染完成后，将它们合并到一个大的 canvas 上
        Promise.all(loadPagePromises).then(function () {
          const combinedCanvas = document.createElement("canvas");
          const combinedContext = combinedCanvas.getContext("2d");
          combinedCanvas.height = totalHeight;
          combinedCanvas.width = maxWidth;

          let currentY = 0;
          for (let i = 0; i < pageCanvases.length; i++) {
            const pageCanvas = pageCanvases[i];
            combinedContext.drawImage(pageCanvas, 0, currentY);
            currentY += pageCanvas.height;
          }

          const img = document.createElement("img");
          img.src = combinedCanvas.toDataURL("image/png");
          pdfContainer.appendChild(img);
        });
      });
    </script>
  </body>
</html>
